from protolib import rgb_to_hex

from PyQt5.QtWidgets import QWidget, QHBoxLayout, QFrame, QComboBox, QSizePolicy
from PyQt5.QtGui import QColor

class ColorPickerWidget(QWidget):
    def __init__(self, parent=None, palette=None):
        super(ColorPickerWidget, self).__init__(parent)

        if palette:
            self.color_palette = [QColor(color) for color in palette]
        else:
            self.color_palette = [
                QColor(0, 0, 0),  # Black
                QColor(255, 0, 0),  # Red
                QColor(0, 255, 0),  # Green
                QColor(0, 0, 255),  # Blue
                QColor(255, 255, 0),  # Yellow
                QColor(255, 0, 255),  # Magenta
                QColor(0, 255, 255),  # Cyan
                QColor(255, 255, 255),  # White
            ]

        self.initUI()

    def initUI(self):
        layout = QHBoxLayout()

        self.color_frame = QFrame(self)
        self.color_frame.setFixedSize(20, 20)  # Set fixed size for color frame
        self.color_frame.setStyleSheet("QFrame { background-color: %s }" % self.color_palette[0].name())

        self.color_combo = QComboBox(self)
        self.color_combo.addItems([rgb_to_hex(i.getRgb()).upper() for i in self.color_palette])
        self.color_combo.currentIndexChanged.connect(self.updateColor)

        layout.addWidget(self.color_frame)
        layout.addWidget(self.color_combo)

        self.setLayout(layout)
        self.updateColor()  # Set initial color

        # Set size policy
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

    def updateColor(self):
        selected_color = self.color_palette[self.color_combo.currentIndex()]
        self.color_frame.setStyleSheet("QFrame { background-color: %s }" % selected_color.name())

    def getColor(self):
        return self.color_palette[self.color_combo.currentIndex()]

    def getColorIndex(self):
        return self.color_combo.currentIndex()
